//
// Created by lester on 2023/12/21.
//

#ifndef TEST_FILE_H
#define TEST_FILE_H
#include <cstring>
#include <functional>
#include <map>
#include <fcntl.h>
#include <unistd.h>
class AppendFile{
public:
    explicit AppendFile(const std::string& filePath) : file_path_(filePath){
        fd_ = open(filePath.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);
        if(fd_ < 0){
            perror("open file failed\n");
            open_succ_ = false;
        }
    }

    bool OpenSuccess() const{
        return open_succ_;
    }

    void Append(const char* data,size_t size){
        if(OpenSuccess()){
            size_t has_write {0};
            size_t remain {0};
            while(has_write !=  size){
                remain = size - has_write;
                size_t write_len = write(fd_,data + has_write,remain);
                has_write += write_len;
                write_bytes += write_len;
            }
        }
    }

    uint64_t GetWriteBytes() const{
        return write_bytes;
    }

    ~AppendFile(){
        if(fd_){
            ::close(fd_);
        }
    }
private:
    std::string file_path_;
    int fd_{};
    bool open_succ_{true};
    uint64_t write_bytes{0};
};

#endif //TEST_FILE_H
